package io.renren.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * <p>
 * 类名
 * </p>
 * http接口处理
 *
 * @author Administrator
 * @version 1.0
 */
public class HttpClientUtil {

    /**
     * <p>
     * 方法名
     * </p>
     * 调用第三方接口
     *
     * @param surl 调用接口名称
     * @return
     */
    public static String getStaticPage(String surl) {
        String htmlContent = "";
        try {
            java.io.InputStream inputStream;
            java.net.URL url = new java.net.URL(surl);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            connection.connect();
            inputStream = connection.getInputStream();
            byte[] bytes = new byte[1024 * 2000];
            int index = 0;
            int count = inputStream.read(bytes, index, 1024 * 2000);
            while (count != -1) {
                index += count;
                count = inputStream.read(bytes, index, 1);
            }
            htmlContent = new String(bytes, "gb2312");
            connection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return htmlContent.trim();
    }

    /**
     * <p>
     * 方法名
     * </p>
     * http请求
     *
     * @param requestUrl 请求地址
     * @param outputStr  请求参数
     * @return
     */
    public static String httpRequest(String requestUrl, String outputStr) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection uploadConn = (HttpURLConnection) url.openConnection();
            uploadConn.setDoOutput(true);
            uploadConn.setRequestProperty("Content-Type", "application/json");
            uploadConn.setDoInput(true);
            // post请求
            uploadConn.setRequestMethod("POST");

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = uploadConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = uploadConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            uploadConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(buffer.toString());
        return buffer.toString();
    }


    public static String httpRequestWithType(String requestUrl, String type, String outputStr, String token) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection uploadConn = (HttpURLConnection) url.openConnection();
            uploadConn.setDoOutput(true);
            uploadConn.setRequestProperty("Content-Type", "application/json");
            uploadConn.setRequestProperty("Authorization", "Bearer " + token);
            uploadConn.setDoInput(true);
            // post请求
            uploadConn.setRequestMethod(type.toUpperCase());

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = uploadConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = uploadConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            uploadConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(buffer.toString());
        return buffer.toString();
    }

    /**
     * 根据ip获取城市
     * <p>
     * 方法名
     * </p>
     * 方法描述
     *
     * @param ip 地址
     */
    public static String getCity(String ip) {
        String src = getStaticPage("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
        // src = src.substring(src.indexOf("{"), src.indexOf("}") + 1);
        JSONObject dataJson = JSONObject.parseObject(src);
        String city = dataJson.getJSONObject("data").getString("city");
        return city;
    }

    /**
     * 根据ip获取城市
     * <p>
     * 方法名
     * </p>
     * 方法描述
     *
     * @param ip 地址
     */
    public static HashMap<String, String> getCityAndCityId(String ip) {
        String src = getStaticPage("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
        HashMap<String, String> cityInfo = new HashMap<String, String>();
        JSONObject dataJson = JSON.parseObject(src);
        String city = dataJson.getJSONObject("data").getString("city");
        String city_id = dataJson.getJSONObject("data").getString("city_id");
        cityInfo.put("city", city);
        cityInfo.put("city_id", city_id);
        return cityInfo;
    }

    /**
     * <p>
     * 方法名
     * </p>
     * 获取手机号码归属地
     *
     * @param mobile 手机号
     * @return 归属地
     */
    public static String getMobileCity(String mobile) {
        String mobileCity = "";
        try {
            Document doc = Jsoup.connect("http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + mobile).get();
            Element body = doc.body();
            Document doc2 = Jsoup.parse(body.toString());
            // @SuppressWarnings("unused")
            // Elements links = doc2.select("a[href]").remove();
            // @SuppressWarnings("unused")
            // Elements text2 = doc2.select("tr").select("td");
            // String result1 = doc2.select("tr").select("td").get(4).text();
            String result2 = doc2.select("tr").select("td").get(6).text();
            // String result3 = doc2.select("tr").select("td").get(8).text();
            // String result4 = doc2.select("tr").select("td").get(10).text();
            // String result5 = doc2.select("tr").select("td").get(12).text();

            // mobileCity = new String(result2.getBytes(), "utf-8");
            mobileCity = result2;
            // String type = new String(result3.getBytes(), "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return mobileCity;
    }

    public static void main(String[] args) {

        String src2 = getMobileCity("18560191373");
        // src = src.substring(src.indexOf("{"), src.indexOf("}") + 1);
        // JSONObject dataJson = JSONObject.fromObject(src);
        System.out.println(src2);
    }
}